/* SharePoint Console Project
 * Http://SharePointConsole.codeplex.com
 * Copyright Jean-Alain Baeyens (2009)
 * Software under Microsoft Reciprocal License (Ms-RL)
 */

using System;
using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using Sharepoint.Console.Commands;

namespace Sharepoint.Console.WebParts
{
    public class RemoveWebPart : RecursiveBaseCommande
    {
        public override string ShortHelp
        {
            get
            {
                return "Remove a webpart from a page";
            }
        }

        public override string LongHelp
        {
            get
            {
                return "Remove a web part from a page using the title of the web part. If more than one web part exist with this title, the first is removed.";
            }
        }

        public override string Syntax
        {
            get
            {
                return "RemoveWebPart 'PageUrl' 'WebPartTitle'";
            }
        }

        public override string Execute(string[] args)
        {
            if (args.Length != 3) return string.Format("Invalide syntax. Use {0}", Syntax);
            
            SPLimitedWebPartManager wpm = null;
            System.Web.UI.WebControls.WebParts.WebPart wp = null;

            string page = args[1];
            string title = args[2];
            
            try
            {
                wpm = this.SharepointConnection.Web.GetLimitedWebPartManager(page, PersonalizationScope.Shared);
                
                SharepointHelper helper = new SharepointHelper();
                
                wp = helper.GetWebPart(wpm, title);
            
                if (wp != null)
                {
                    wpm.DeleteWebPart(wp);
                
                    return "Webpart deleted";
                }
                
                else
                {
                    return "Webpart not found";
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
